﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WpfApp.Update
{
    public static class DirectoryCopier
    {
        /// <summary>
        /// 同步拷贝文件夹及其所有内容
        /// </summary>
        /// <param name="sourceDir">源文件夹路径</param>
        /// <param name="destinationDir">目标文件夹路径</param>
        /// <param name="overwrite">是否覆盖已存在的文件</param>
        public static void CopyDirectory(string sourceDir, string destinationDir, bool overwrite = true)
        {
            if (string.IsNullOrWhiteSpace(sourceDir))
                throw new ArgumentException("源文件夹路径不能为空", nameof(sourceDir));

            if (string.IsNullOrWhiteSpace(destinationDir))
                throw new ArgumentException("目标文件夹路径不能为空", nameof(destinationDir));

            // 检查源文件夹是否存在
            var sourceDirectory = new DirectoryInfo(sourceDir);
            if (!sourceDirectory.Exists)
                throw new DirectoryNotFoundException($"源文件夹不存在: {sourceDir}");

            // 确保目标文件夹存在
            Directory.CreateDirectory(destinationDir);

            // 拷贝所有文件
            foreach (var file in sourceDirectory.GetFiles())
            {
                string destFilePath = Path.Combine(destinationDir, file.Name);
                file.CopyTo(destFilePath, overwrite);
            }

            // 递归拷贝所有子文件夹
            foreach (var subDir in sourceDirectory.GetDirectories())
            {
                string destSubDir = Path.Combine(destinationDir, subDir.Name);
                CopyDirectory(subDir.FullName, destSubDir, overwrite);
            }
        }

        /// <summary>
        /// 异步拷贝文件夹及其所有内容
        /// </summary>
        public static async Task CopyDirectoryAsync(string sourceDir, string destinationDir, bool overwrite = true, IProgress<double>? progress = null)
        {
            if (string.IsNullOrWhiteSpace(sourceDir))
                throw new ArgumentException("源文件夹路径不能为空", nameof(sourceDir));

            if (string.IsNullOrWhiteSpace(destinationDir))
                throw new ArgumentException("目标文件夹路径不能为空", nameof(destinationDir));

            var sourceDirectory = new DirectoryInfo(sourceDir);
            if (!sourceDirectory.Exists)
                throw new DirectoryNotFoundException($"源文件夹不存在: {sourceDir}");

            // 获取所有文件用于进度计算
            var allFiles = sourceDirectory.GetFiles("*", SearchOption.AllDirectories);
            int totalFiles = allFiles.Length;
            int copiedFiles = 0;

            // 确保目标文件夹存在
            Directory.CreateDirectory(destinationDir);

            // 使用并行处理提高大文件拷贝性能
            var options = new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount };

            await Task.Run(() =>
            {
                Parallel.ForEach(allFiles, options, file =>
                {
                    string relativePath = file.FullName.Substring(sourceDirectory.FullName.Length + 1);
                    string destFilePath = Path.Combine(destinationDir, relativePath);

                    // 确保目标目录存在
                    string? destDir = Path.GetDirectoryName(destFilePath);
                    if (!string.IsNullOrEmpty(destDir))
                    {
                        Directory.CreateDirectory(destDir);
                    }

                    file.CopyTo(destFilePath, overwrite);

                    // 更新进度
                    if (progress != null)
                    {
                        int current = Interlocked.Increment(ref copiedFiles);
                        double percentage = (double)current / totalFiles * 100;
                        progress.Report(percentage);
                    }
                });
            });
        }
    }
}
